/**
 * 
 */
package com.qianhai.manage.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qianhai.manage.service.ICompetitionService;
import com.qianhai.manage.service.INewsTypeService;
import com.qianhai.manage.util.StringUtil;
import com.qianhai.manage.util.TransformationUtil;
import com.qianhai.manage.vo.AwardPrizes;
import com.qianhai.manage.vo.CompetitionInfo;
import com.qianhai.manage.vo.NewsTypeInfo;

/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping("competition")
public class CompetitionController extends BaseController {
	
	private final static String PATH = "/root/show-web/lib/webapp/static/wx_static/site_media/html";
//	private final static String PATH = "C:\\Program Files (x86)\\Apache Software Foundation\\Tomcat 7.0\\webapps\\qhmanage\\upload/html";
	
	@Resource
	private ICompetitionService competitionService;
	
	@Resource
	private INewsTypeService newsTypeService;
	
	@RequestMapping("competitionmanage")
	public String toCompetitionmanage() {
		return "competition/competitionmanage";
	}
	
	@RequestMapping("awardprizes")
	public String toAwardPrizes() {
		return "competition/sendprize";
	}
	
	@RequestMapping("editcompetition")
	public String toEditCompetition(CompetitionInfo vo, ModelMap map) {
		if(vo != null && !StringUtil.isEmpty(vo.getCid())) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("cid", vo.getCid());
			List<CompetitionInfo> list = this.competitionService.selectCompetitionInfos(param, 0, 0);
			if(list == null || list.isEmpty()) {
				return "error";
			}
			this.setNewsContent(list);
			vo = list.get(0);
			map.put("vo", vo);
		} else {
			String pid = UUID.randomUUID().toString().replace("-", "");
			map.put("pid", pid);
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("value", 3);
		List<NewsTypeInfo> newstypes = this.newsTypeService.selectNewsTypeInfos(param, 0, 0);
		if(newstypes != null && !newstypes.isEmpty()) {
			NewsTypeInfo info = newstypes.get(0);
			map.put("leveltid", info.getCid());
		}
		return "competition/editcompetition";
	}
	
	@ResponseBody
	@RequestMapping("querycompetition")
	public Map<String, Object> queryCompetition(HttpServletRequest request, CompetitionInfo vo) {
		Map<String, Object> result = new HashMap<String, Object>();
		int page = this.getPage(request);
		int rows = this.getRows(request);
		Map<String, Object> param = TransformationUtil.Object2HashMap(vo);
		param.put("type", vo.getType());
		param.put("levelt", vo.getLevelt());
		param.put("cost", vo.getCost());
		param.put("sort", "create_time desc");
		List<CompetitionInfo> list =  this.competitionService.selectCompetitionInfos(param, page, rows);
		this.setNewsContent(list);
		long count = this.competitionService.countCompetitionInfos(param);
		result.put("rows", list);
		result.put("total", count);
		return result;
	}
	
	@ResponseBody
	@RequestMapping("savecompetition")
	public Map<String, Object> saveCompetition(HttpServletRequest request, CompetitionInfo vo) {
		Map<String, Object> result = new HashMap<>();
		Object _username = request.getSession().getAttribute("username");
		if(_username == null) {
			_username = "";
		}
		String username = StringUtil.addDefault(_username.toString(), "Admin");
		String content = vo.getContent();
		if(StringUtil.isEmpty(vo.getCid())) {
			vo.setCreator(username);
			String cid = request.getParameter("pid");
			vo.setCid(cid);
			String filePath = PATH + "/" + cid + ".html";
			vo.setContent(filePath);
			this.competitionService.saveCompetitionInfo(vo);
			result.put("result", 1);
		} else {
			vo.setModifiedPerson(username);
			vo.setContent(null);
			this.competitionService.updateCompetitionInfo(vo);
			result.put("result", 2);
		}
		try {
			this.saveHtml(vo.getCid(), content);
		} catch (IOException e) {
			result.put("result", 3);
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping("deletecompetition")
	public Map<String, Object> deletecompetition(HttpServletRequest request, String cids) {
		Map<String, Object> result = new HashMap<String, Object>();
		if(StringUtil.isEmpty(cids)) {
			return result;
		}
		String[] _cids = cids.split(",");
		List<String> cidl = Arrays.asList(_cids);
		this.deleteCompetition(request, cidl);
		result.put("result", 1);
		return result;
	}
	
	private void saveHtml(String cid, String content) throws IOException {
		File dirPath = new File(PATH);
		if(!dirPath.exists()) {
			dirPath.mkdirs();
		}
		String filePath = PATH + "/" + cid + ".html";
		File html = new File(filePath);
		if(!html.exists()) {
			html.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(html);
		fos.write(content.getBytes());
		fos.flush();
		fos.close();
	}
	
	private void setNewsContent(List<CompetitionInfo> list) {
		if(list != null && !list.isEmpty()) {
			for(CompetitionInfo vo : list) {
				String content = vo.getContent();
				StringBuffer sb = new StringBuffer();
				if(content.startsWith(PATH)) {
					BufferedReader reader = null;
					try {
						File html = new File(content);
						FileReader fr = new FileReader(html);
						reader = new BufferedReader(fr);
						String tempString = null;
						while((tempString = reader.readLine()) != null) {
							sb.append(tempString);
						}
						reader.close();
						String _content = sb.toString();
						_content = _content.replace("\'", "\\\'");
						vo.setContent(_content);
					} catch(Exception e) {
						e.printStackTrace();
					} finally {
						if(reader != null) {
							try {
								reader.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
				
			}
		}
	}
	
	private void deleteCompetition(HttpServletRequest request, List<String> cids) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("cids", cids);
		List<CompetitionInfo> list = this.competitionService.selectCompetitionInfos(param, 0, 0);
		if(list != null && !list.isEmpty()) {
			for(CompetitionInfo info : list) {
				
				String content = info.getContent();
				if(!StringUtil.isEmpty(content)) {
					File file = new File(content);
					if(file.exists()) {
						file.delete();
					}
				}
			}
			this.competitionService.deleteCompetitionInfo(cids);
		}
	}
	
	@ResponseBody
	@RequestMapping("queryprize")
	public Map<String, Object> queryprize(HttpServletRequest request, AwardPrizes vo) {
		Map<String, Object> result = new HashMap<String, Object>();
		int page = this.getPage(request);
		int rows = this.getRows(request);
		Map<String, Object> param = TransformationUtil.Object2HashMap(vo);
		List<AwardPrizes> list = this.competitionService.queryPrizes(param, page, rows);
		long count = this.competitionService.countPrizes(param);
		result.put("rows", list);
		result.put("total", count);
		return result;
	}
	
	@ResponseBody
	@RequestMapping("updatePrizeState")
	public Map<String, Object> updatePrizeState(HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		String json = request.getParameter("json");
		if(StringUtil.isEmpty(json)) {
			result.put("result", 0);
			return result;
		}
		if(!json.startsWith("[") && !json.endsWith("]")) {
			json = "[" + json + "]";
		}
		List<Map<String, Object>> list = TransformationUtil.JSONString2ArrayList(json);
		this.competitionService.updatePrizes(list);
		result.put("result", 1);
		return result;
	}

}
